﻿using System;
using System.Web.UI;
using WeiBeeCommon.Core;
using System.Collections.Generic;
using System.IO;
using System.Web.UI.WebControls;
using System.Text;
using WeiBeeCommon.Helpers;

public partial class _Default : Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Session[Guid.NewGuid().ToString()] = 1;
        if ( Session["webuser"] != null)
        {
            SetVisibilityForUserLoggedIn();
        }
        if (!Page.IsPostBack)
        {
            if (Request["oauth_verifier"] != null)
            {
                foreach (var t in WeiBeeTypes)
                {
                    if (Session["weibeetype"] != null)
                    {
                        if (string.Compare(Session["weibeetype"].ToString(), t.ToString()) == 0)
                        {
                            AccessTokenGet(t);
                            break;
                        }
                    }
                }
                Response.Redirect("Default.aspx");
            }
            if (!AnyAccountLogin())
            {
                lbLoginStatus.Text = "还没登录呢!";
                imageButtonLogin.Visible = true;
                imageButtonSend.Visible = false;
            }
            else
            {
                ShowLoginInfomation();
            }
        }
    }

    private void ShowLoginInfomation()
    {
        StringBuilder sb = new StringBuilder();
        foreach (var t in TokenSessionNameDict)
        {
            if (Session[t.Value] != null)
            {
                sb.Append(_weiBeeNameStringDict[t.Key]);
                WeiBeeButtonDict[t.Key].Visible = false;
            }
        }
        sb.Append("已经登录");
        lbLoginStatus.Text = sb.ToString();
    }

    private bool AnyAccountLogin()
    {
        foreach(var t in TokenSessionNameDict)
        {
            if (Session[t.Value] != null)
            {
                return true;
            }
        }
        return false;
    }

    private void AccessTokenGet(WeiBeeType wbType)
    {
        var weibee = WeiBeeFactory.CreateWeiBeeByType(wbType);
        weibee.SetOAuth(Session[GetTokenSessionName(wbType)].ToString(), Session[GetTokenSecretSessionName(wbType)].ToString());
        weibee.GetOAuth().Verifier = Request["oauth_verifier"];
        weibee.GetOAuth().AccessTokenGet(Request["oauth_token"], Request["oauth_verifier"]);
        Session[GetTokenSessionName(wbType)] = weibee.GetOAuth().Token;
        Session[GetTokenSecretSessionName(wbType)] = weibee.GetOAuth().TokenSecret;
        // Save binging Wei Bo for logged in user
        if (Session["webuser"] != null)
        {
            var helper = new WebUserHelper(_webUserStore);
            helper.UpdateWeiBeeInfo(Session["webuser"].ToString(), weibee);
        }
    }

    protected void ImageButtonLoginClick(object sender, ImageClickEventArgs e)
    {
        OpenAuthPage();
    }

    private string callbackurl = System.Configuration.ConfigurationManager.AppSettings["rooturl"];

    void OpenAuthPage()
    {
        OpenAuthPage(WeiBeeType.QQ);
    }

    void OpenAuthPage(WeiBeeType wbType)
    {
        IWeiBee weibee = WeiBeeFactory.CreateWeiBeeByType(wbType);
        weibee.GetOAuth().SetCallbackUrl(callbackurl);
        string authenticationUrl = weibee.GetOAuth().AuthorizationLinkGet();
        Session[GetTokenSessionName(wbType)] = weibee.GetOAuth().Token;
        Session[GetTokenSecretSessionName(wbType)] = weibee.GetOAuth().TokenSecret;
        Session["weibeetype"] = weibee.UserType.ToString();
        Response.Redirect(authenticationUrl);
    }

    protected void BtnSendClick(object sender, ImageClickEventArgs e)
    {
        foreach (var t in TokenSessionNameDict)
        {
            if (Session[t.Value] != null)
            {
                AddTwitter(t.Key);
            }
        }
    }

    private void AddTwitter(WeiBeeType wbType)
    {
        var add = new WeiBeeAdd(
            Session[GetTokenSessionName(wbType)].ToString(),
            Session[GetTokenSecretSessionName(wbType)].ToString(),
            wbType,
            tbMessage.Text);
        if (cbSchedule.Checked)
        {
            add.ScheduledTime = Utility.ParseDateTime(tbScheduledTime.Text).ToUniversalTime();
        }
        if (picfileupload.HasFile)
        {
            add.PictureFile = UploadToServer();
        }
        TimedJob.GetInstance().Add(add);
    }

    private string UploadToServer()
    {
        string filename = Guid.NewGuid().ToString("N") + Path.GetExtension(picfileupload.FileName).ToLower();
        string fname = Server.MapPath(filename);
        lbLoginStatus.Text = fname;
        picfileupload.SaveAs(fname);
        return fname;
    }

    protected void ImageButtonLoginSohuClick(object sender, ImageClickEventArgs e)
    {
        OpenAuthPage(WeiBeeType.Sohu);
    }

    protected void ImageButtonLoginSinaClick(object sender, ImageClickEventArgs e)
    {
        OpenAuthPage(WeiBeeType.Sina);
    }

    #region SessionNames
    static readonly Dictionary<WeiBeeType, string> TokenSessionNameDict = new Dictionary<WeiBeeType, string>
                                                                              { 
                {WeiBeeType.QQ, "oauth_token" },
                {WeiBeeType.Sohu, "SohuToken" },
                {WeiBeeType.Sina, "SinaToken" }
            };
    string GetTokenSessionName(WeiBeeType wbType)
    {
        return TokenSessionNameDict[wbType];
    }

    static readonly Dictionary<WeiBeeType, string> TokenSecretSessionNameDict = new Dictionary<WeiBeeType, string>
            { 
                {WeiBeeType.QQ, "oauth_token_secret" },
                {WeiBeeType.Sohu, "SohuTokenSecret" },
                {WeiBeeType.Sina, "SinaTokenSecret" }
            };
    string GetTokenSecretSessionName(WeiBeeType wbType)
    {
        return TokenSecretSessionNameDict[wbType];
    }

    private Dictionary<WeiBeeType, ImageButton> WeiBeeButtonDict = new Dictionary<WeiBeeType, ImageButton>();

    protected void Page_InitComplete(object sender, EventArgs e)
    {
        WeiBeeButtonDict.Add(WeiBeeType.QQ, imageButtonLogin );
        WeiBeeButtonDict.Add(WeiBeeType.Sohu, imageButtonLoginSohu);
        WeiBeeButtonDict.Add(WeiBeeType.Sina, imageButtonLoginSina);
        InitDdList();
        _webUserStore = Server.MapPath("webusers.xml");
    }

    private readonly Dictionary<WeiBeeType, string> _weiBeeNameStringDict = new Dictionary<WeiBeeType,string>
           { 
                {WeiBeeType.QQ, "腾讯" },
                {WeiBeeType.Sohu, "搜狐" },
                {WeiBeeType.Sina, "新浪" }
            };
    private List<WeiBeeType> WeiBeeTypes = new List<WeiBeeType>
    {
        WeiBeeType.QQ, WeiBeeType.Sohu, WeiBeeType.Sina
    };            
    #endregion

    protected void CbScheduleCheckedChanged(object sender, EventArgs e)
    {
        //DDListHour.Visible = cbSchedule.Checked;
    }
    private void InitDdList()
    {
        tbScheduledTime.Text = DateTime.Now.ToShortDateString() + " " + DateTime.Now.ToShortTimeString();
    }

    private string _webUserStore;
    protected void BtLoginClick(object sender, EventArgs e)
    {
        var helper = new WebUserHelper(_webUserStore);
        if (helper.IsUserValid(tbUsername.Text.Trim(), tbPwd.Text.Trim()))
        {
            Session["webuser"] = tbUsername.Text;
            var tokens = helper.GetUserTokens(tbUsername.Text);
            foreach (var t in tokens)
            {
                Session[GetTokenSessionName(t.UserType)] = t.Token;
                Session[GetTokenSecretSessionName(t.UserType)] = t.TokenSecret;
            }
            SetVisibilityForUserLoggedIn();
            Response.Redirect("Default.aspx");
        }
        else
        {
            lbLoged.Text = "用户名或者密码错误";
        }
    }

    private void SetVisibilityForUserLoggedIn()
    {
        lbUser.Visible = false;
        lbPwd.Visible = false;
        tbUsername.Visible = false;
        tbPwd.Visible = false;
        btLogin.Visible = false;
        LinkButton1.Visible = false;
        lbLoged.Text = Session["webuser"] + "已登录";
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Response.Redirect("NewUser.aspx");
    }
}

